"""
邮件配置相关的API路由
"""

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import Optional, List

from database import get_db
from schemas.email_config import (
    EmailConfigCreate, EmailConfigUpdate, EmailConfigResponse, EmailConfigList,
    EmailConfigTest, EmailConfigTestResponse, EmailConfigStatistics,
    EmailSendTest, EmailSendTestResponse
)
from services.email_config_service import EmailConfigService
from utils.dependencies import get_current_active_user
from models.user import User

router = APIRouter()


@router.post("/", response_model=EmailConfigResponse, summary="创建邮件配置")
async def create_email_config(
    config_data: EmailConfigCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    创建新的邮件配置
    
    - **name**: 配置名称
    - **smtp_host**: SMTP服务器地址
    - **smtp_port**: SMTP端口
    - **username**: SMTP用户名
    - **password**: SMTP密码
    - **from_email**: 发件人邮箱
    - **from_name**: 发件人姓名（可选）
    - **encryption**: 加密类型（none/ssl/starttls）
    - **timeout**: 连接超时时间
    - **description**: 配置描述（可选）
    """
    config = EmailConfigService.create_email_config(db, config_data, current_user.id)
    return EmailConfigResponse.from_orm(config)


@router.get("/", response_model=EmailConfigList, summary="获取邮件配置列表")
async def get_email_configs(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    active_only: bool = Query(False, description="仅显示启用的配置"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    获取邮件配置列表，支持分页、搜索和状态过滤
    
    - **page**: 页码（从1开始）
    - **size**: 每页数量（1-100）
    - **search**: 搜索关键词（可选）
    - **active_only**: 仅显示启用的配置（可选）
    """
    return EmailConfigService.get_email_configs(db, current_user.id, page, size, search, active_only)


@router.get("/{config_id}", response_model=EmailConfigResponse, summary="获取邮件配置详情")
async def get_email_config(
    config_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    获取指定邮件配置的详细信息
    
    - **config_id**: 邮件配置ID
    """
    config = EmailConfigService.get_email_config(db, config_id, current_user.id)
    if not config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件配置不存在"
        )
    return EmailConfigResponse.from_orm(config)


@router.put("/{config_id}", response_model=EmailConfigResponse, summary="更新邮件配置")
async def update_email_config(
    config_id: int,
    config_data: EmailConfigUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    更新指定邮件配置的信息
    
    - **config_id**: 邮件配置ID
    - **name**: 配置名称（可选）
    - **smtp_host**: SMTP服务器地址（可选）
    - **smtp_port**: SMTP端口（可选）
    - **username**: SMTP用户名（可选）
    - **password**: SMTP密码（可选）
    - **from_email**: 发件人邮箱（可选）
    - **from_name**: 发件人姓名（可选）
    - **encryption**: 加密类型（可选）
    - **timeout**: 连接超时时间（可选）
    - **description**: 配置描述（可选）
    """
    config = EmailConfigService.update_email_config(db, config_id, config_data, current_user.id)
    if not config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件配置不存在"
        )
    return EmailConfigResponse.from_orm(config)


@router.delete("/{config_id}", summary="删除邮件配置")
async def delete_email_config(
    config_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    删除指定的邮件配置
    
    - **config_id**: 邮件配置ID
    """
    success = EmailConfigService.delete_email_config(db, config_id, current_user.id)
    if not success:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件配置不存在"
        )
    return {"message": "邮件配置删除成功"}


@router.post("/{config_id}/toggle", response_model=EmailConfigResponse, summary="切换邮件配置状态")
async def toggle_email_config_status(
    config_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    切换指定邮件配置的启用/禁用状态
    
    - **config_id**: 邮件配置ID
    """
    config = EmailConfigService.toggle_email_config_status(db, config_id, current_user.id)
    if not config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="邮件配置不存在"
        )
    return EmailConfigResponse.from_orm(config)


@router.post("/test", response_model=EmailConfigTestResponse, summary="测试邮件配置")
async def test_email_config(
    test_request: EmailConfigTest,
    current_user: User = Depends(get_current_active_user)
):
    """
    测试邮件配置连接是否正常
    
    - **smtp_host**: SMTP服务器地址
    - **smtp_port**: SMTP端口
    - **username**: SMTP用户名
    - **password**: SMTP密码
    - **from_email**: 发件人邮箱
    - **encryption**: 加密类型
    - **timeout**: 连接超时时间
    - **test_email**: 测试邮件接收地址（可选）
    """
    return EmailConfigService.test_email_config(test_request)


@router.post("/send-test", response_model=EmailSendTestResponse, summary="发送测试邮件")
async def send_test_email(
    send_request: EmailSendTest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    使用指定的邮件配置发送测试邮件
    
    - **config_id**: 邮件配置ID
    - **to_email**: 收件人邮箱
    - **subject**: 邮件主题
    - **content**: 邮件内容
    """
    return EmailConfigService.send_test_email(db, send_request, current_user.id)


@router.get("/statistics", response_model=EmailConfigStatistics, summary="获取邮件配置统计")
async def get_email_config_statistics(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    获取当前用户的邮件配置统计信息
    
    - 总配置数
    - 启用配置数
    - 按加密类型分布
    - 最近7天新增数量
    """
    return EmailConfigService.get_email_config_statistics(db, current_user.id)


@router.get("/active/list", response_model=List[EmailConfigResponse], summary="获取启用的邮件配置")
async def get_active_email_configs(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    获取当前用户所有启用的邮件配置
    """
    configs = EmailConfigService.get_active_email_configs(db, current_user.id)
    return [EmailConfigResponse.from_orm(config) for config in configs]
